
#import "SearchViewController.h"
#import "TorrentDetailsViewController.h"

@implementation SearchViewController

//
// filter pattern
//
@synthesize filterPattern													= _filterPattern;

//
// torrent list
//
@synthesize torrentList														= _torrentList;

//
// page index
//
@synthesize pageIndex														= _pageIndex;

//
// page count
//
@synthesize pageCount														= _pageCount;

//
// home
//
@synthesize homeGesture														= _homeGesture;

//
// page up
//
@synthesize pageUpGesture													= _pageUpGesture;

//
// page down
//
@synthesize pageDownGesture													= _pageDownGesture;

//
// end
//
@synthesize endGesture														= _endGesture;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super initWithStyle:UITableViewStyleGrouped];
	if(!self)
		return nil;
	
	//
	// setup title, image
	//
	self.title																= NSLocalizedStringFromTable(@"Search", @"SearchViewController", nil);
	self.tabBarItem.image													= [UIImage imageNamed:@"tab_icon_search.png"];
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.filterPattern														= nil;
	self.torrentList														= nil;
	self.homeGesture														= nil;
	self.pageUpGesture														= nil;
	self.pageDownGesture													= nil;
	self.endGesture															= nil;
	
	[super dealloc];
}

//
// load
//
- (void)viewDidLoad
{
	[super viewDidLoad];
	
	UISearchBar* searchBar													= [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 0)] autorelease];
	[searchBar sizeToFit];
	searchBar.delegate														= self;
	self.navigationItem.titleView											= searchBar;
	self.navigationItem.titleView.autoresizingMask							= UIViewAutoresizingFlexibleWidth;
	[searchBar setShowsCancelButton:YES];
	
	//
	// create guest
	//
	self.homeGesture														= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.homeGesture.numberOfTouchesRequired								= 2;
	self.homeGesture.direction												= UISwipeGestureRecognizerDirectionLeft;
	[self.tableView addGestureRecognizer:self.homeGesture];
	self.pageUpGesture														= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.pageUpGesture.numberOfTouchesRequired								= 1;
	self.pageUpGesture.direction											= UISwipeGestureRecognizerDirectionLeft;
	[self.tableView addGestureRecognizer:self.pageUpGesture];
	self.pageDownGesture													= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.pageDownGesture.numberOfTouchesRequired							= 1;
	self.pageDownGesture.direction											= UISwipeGestureRecognizerDirectionRight;
	[self.tableView addGestureRecognizer:self.pageDownGesture];
	self.endGesture															= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.endGesture.numberOfTouchesRequired									= 2;
	self.endGesture.direction												= UISwipeGestureRecognizerDirectionRight;
	[self.tableView addGestureRecognizer:self.endGesture];
}

//
// will appear
//
- (void)viewWillAppear:(BOOL)animated
{
	[self.tableView reloadRowsAtIndexPaths:self.tableView.indexPathsForSelectedRows withRowAnimation:UITableViewRowAnimationNone];
	[super viewWillAppear:animated];
}

//
// get section count
//
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return 1;
}

//
// get row count
//
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return self.torrentList.count;
}

//
// get title
//
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
	if(!self.filterPattern)
		return nil;
	
	return [NSString stringWithFormat:NSLocalizedStringFromTable(@"Result Page (%d/%d)", @"SearchViewController", nil), self.pageIndex + 1, self.pageCount];
}

//
// get cell
//
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	TorrentListViewCell* theCell											= [tableView dequeueReusableCellWithIdentifier:@"s>"];
	if(!theCell)
		theCell																= [[[TorrentListViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"s>"] autorelease];
	
	TorrentInfo* info														= [self.torrentList objectAtIndex:indexPath.row];
	theCell.nameLabel.text													= info.title;
	theCell.timeLabel.text													= info.uploadDate;
	theCell.categoryLabel.text												= info.category;
	theCell.sizeLabel.text													= info.size;
	[theCell setupImageWithUnread:info.unread sticky:info.sticky upRate:info.upRate downRate:info.downRate];
	theCell.accessoryType													= UITableViewCellAccessoryDisclosureIndicator;
	theCell.detailTextLabel.textColor										= info.unread ? [UIColor redColor] : [UIColor grayColor];
	return theCell;
}

//
// get height
//
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
	return [TorrentListViewCell rowHeight];
}

//
// select row
//
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	TorrentInfo* info														= [self.torrentList objectAtIndex:indexPath.row];
	if(info.unread)
	{
		[[DataCenter sharedDataCenter] markAsReadForTorrentId:info.torrentId];
		info.unread															= NO;
		[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
	}
	TorrentDetailsViewController* torrentDetailsViewController				= [[[TorrentDetailsViewController alloc] init] autorelease];
	torrentDetailsViewController.torrentInfo								= info;
	[self.navigationController pushViewController:torrentDetailsViewController animated:YES];
}

//
// search
//
- (void)searchTorrent
{
	NexusClient* client														= [NexusClient sharedClient];
	id searchTorrentCallback = ^void(GetTorrentListRequest* httpRequest)
	{
		[ActivityView removeView];
		if(!httpRequest.error && httpRequest.response.statusCode == 200)
		{
			self.torrentList												= httpRequest.torrentList;
			self.pageIndex													= httpRequest.pageIndex;
			self.pageCount													= httpRequest.pageCount;
			DataCenter* dataCenter											= [DataCenter sharedDataCenter];
			for(TorrentInfo* info in self.torrentList)
				[dataCenter checkAddTorrent:info];

			[self.tableView reloadData];
		}
		else
		{
			NSString* message												= [httpRequest errorDescription];
			NSString* title													= NSLocalizedStringFromTable(@"Search Torrent Failed", @"SearchViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
		}
	};
	[ActivityView showActivityView:NSLocalizedStringFromTable(@"Searching Torrent", @"SearchViewController", nil) networking:YES];
	[client searchTorrentWithPattern:self.filterPattern pageIndex:self.pageIndex callback:searchTorrentCallback];
}

//
// search item
//
- (void)searchBarSearchButtonClicked:(UISearchBar*)searchBar
{
	[searchBar resignFirstResponder];
	if(!searchBar.text.length)
		return;
	
	self.pageIndex															= 0;
	self.pageCount															= 0;
	self.filterPattern														= searchBar.text;
	[self searchTorrent];
}

//
// cancel
//
- (void)searchBarCancelButtonClicked:(UISearchBar*)searchBar
{
	[searchBar resignFirstResponder];
}

//
// swipe gesture
//
- (void)swipeGestureRecognized:(UISwipeGestureRecognizer*)gesture
{
	switch(gesture.direction)
	{
	case UISwipeGestureRecognizerDirectionLeft:
		if(gesture.numberOfTouches == 1)
		{
			if(self.pageIndex)
			{
				self.pageIndex												-= 1;
				[self searchTorrent];
			}
		}
		else if(gesture.numberOfTouches == 2)
		{
			if(self.pageIndex)
			{
				self.pageIndex												= 0;
				[self searchTorrent];
			}
		}
		break;
		
	case UISwipeGestureRecognizerDirectionRight:
		if(gesture.numberOfTouches == 1)
		{
			if(self.pageIndex < self.pageCount - 1)
			{
				self.pageIndex												+= 1;
				[self searchTorrent];
			}
		}
		else if(gesture.numberOfTouches == 2)
		{
			if(self.pageIndex != self.pageCount - 1)
			{
				self.pageIndex												= self.pageCount - 1;
				[self searchTorrent];
			}
		}
		break;
			
	default:
		break;
	}
}

@end
